package org.example.json;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.core.Version;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.base.Strings;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author: feiwang_6
 * @create: 2020/10/23 14:53
 * @description: JSON序列化工具
 */
public class JsonUtils {
    private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
    private static ObjectMapper objectMapper = new ObjectMapper();

    private JsonUtils() {
    }
    
    static {
        objectMapper.setSerializationInclusion(Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
        objectMapper.configure(Feature.ALLOW_COMMENTS, true);
        objectMapper.configure(Feature.ALLOW_NON_NUMERIC_NUMBERS, true);
        objectMapper.configure(Feature.ALLOW_NUMERIC_LEADING_ZEROS, true);
        objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        objectMapper.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        //DateTime解析器
        SimpleModule module = new SimpleModule("DateTimeModule", Version.unknownVersion());
        module.addDeserializer(DateTime.class, new DateTimeDeserializer());
        module.addSerializer(DateTime.class, new DateTimeSerializer());
        objectMapper.registerModule(module);
    }

    /**
     * 序列化
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String encode(T obj) {
        if (Objects.isNull(obj)) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            logger.error("json encode error, obj={}", obj, e);
            return null;
        }
    }

    /**
     * 反序列化
     * @param json
     * @param valueType
     * @param <T>
     * @return
     */
    public static <T> T decode(String json, Class<T> valueType) {
        if (!Strings.isNullOrEmpty(json) && !Objects.isNull(valueType)) {
            try {
                return objectMapper.readValue(json, valueType);
            } catch (Exception e) {
                logger.error("json decode fail,jsonString={}, type={}", json, valueType.getName(), e);
            }
        }
        return null;
    }

    /**
     * 反序列化成list
     * @param json
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> List<T> decode2List(String json, Class<T> clazz) {
        if (!Strings.isNullOrEmpty(json) && !Objects.isNull(clazz)) {
            try {
                return (List) objectMapper.readValue(json, objectMapper.getTypeFactory().constructCollectionType(List.class, clazz));
            } catch (Exception var3) {
                logger.error("json decode2list fail,json={},classType={}", new Object[]{json, clazz.getName(), var3});
            }
        }
        return null;
    }

    /**
     * map转clazz对象
     * @param map
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T mapToObject(Map map, Class<T> clazz) {
        String json = null;
        try {
            json = objectMapper.writeValueAsString(map);
            return objectMapper.readValue(json, clazz);
        } catch (Exception e) {
            logger.error("json map2object fail,map={},ClassName={}", json, clazz.getName());
            return null;
        }
    }

    /**
     * 将JSONObject解析成map
     * @param prefix key名称前缀
     * @param obj JSONObject对象
     * @param map
     */
    public static void decodeJSONObject(String prefix, Object obj, Map<String, Object> map) {
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            Iterator keys = ((JSONObject) obj).keySet().iterator();
            while (true) {
                while (keys.hasNext()) {
                    String key = (String) keys.next();
                    Object o = json.get(key);
                    String pre = String.join(".", prefix, key);
                    if (!(o instanceof JSONObject) && !(o instanceof JSONArray)) {
                        map.put(pre, o);
                    } else {
                        decodeJSONObject(pre, o, map);
                    }
                }
                return;
            }
        } else if (obj instanceof JSONArray) {
            Iterator iterator = ((JSONArray) obj).iterator();
            while (true) {
                while (iterator.hasNext()) {
                    Object ob = iterator.next();
                    if (!(ob instanceof JSONObject) && !(ob instanceof JSONArray)) {
                        map.put(prefix, ob);
                    } else {
                        decodeJSONObject(prefix, ob, map);
                    }
                }
                return;
            }
        }
    }
}
